
#include "PLCP_sw_timer.h"

#define SW_TIMERS_MNG_MAX_TIMERS	16
static SW_TIMER_STRUCT sw_timers[SW_TIMERS_MNG_MAX_TIMERS];

static U8 sw_timers_mng_check_free(SW_TIMER_STRUCT* sw_timer)
{
	if((sw_timer->counter == 0)
	&&(sw_timer->interval == 0)
	&&(sw_timer->param == 0)
	&&(sw_timer->state.enable == 0)
	&&(sw_timer->state.cyclic == 0)
	&&(sw_timer->state.timeout == 0)
	&&(sw_timer->timeout_callback == 0)){
		return 1;
	}
	else{
		return 0;
	}
}

SW_TIMER_STRUCT* sw_timers_mng_new(void)
{
	U8 i;
	for (i = 0; i < SW_TIMERS_MNG_MAX_TIMERS; i++) {
		if(sw_timers_mng_check_free(&(sw_timers[i])))
		{
			LOGINFO1(UART_DEBUG, "sw timer new id %d\n", i);
			return &(sw_timers[i]);
		}
	}
	LOGINFO0(UART_DEBUG, "sw timer new fail!\n");
	return 0;
}

U8 sw_timers_mng_del(SW_TIMER_STRUCT* sw_timer)
{
	if(sw_timer != 0){
		sw_timer->counter = 0;
		sw_timer->interval = 0;
		sw_timer->param = 0;
		sw_timer->state.enable = 0;
		sw_timer->state.cyclic = 0;
		sw_timer->state.timeout = 0;
		sw_timer->timeout_callback = 0;
		return 1;
	}
	return 0;
}

void sw_timers_mng_tick_handler(U32 ticks)
{
	U8 i;
	for (i = 0; i < SW_TIMERS_MNG_MAX_TIMERS; i++) {
		if(!sw_timers_mng_check_free(&(sw_timers[i])))
		{
			sw_timer_tick_handler(&(sw_timers[i]), ticks);
		}
	}
}

void sw_timers_mng_init(void)
{
	U8 i;
	for (i = 0; i < SW_TIMERS_MNG_MAX_TIMERS; i++) {
		sw_timers_mng_del(&(sw_timers[i]));
	}	
}
